/**
 * @description 组织机构页面
 * @author 李艳
 */
import React, {Component} from "react";

import {deleteNode, getOrganizationTree, move, save} from "./OrganizationService";
import {Input,Button, Checkbox, Col, Form, InputNumber, message,Row,Modal} from "antd";
import {hide, show} from "../../../configs/SharedReducer";
import connect from "react-redux/es/connect/connect";
import EditOrganizationModal from "./EditOrganizationModal";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import DetailCard from "../../../commons/components/DetailCard";
import {rowGutter} from "../../../configs/DefaultConfig";
import StandardTree from "../../../commons/components/StandardTree";
import PageOperateHoc from "../../../commons/components/PageOperateHoc";
import CheckAuth from "../../../commons/components/CheckAuth/index.jsx";
import {checkInputCode} from "../../../commons/utils/CommonUtils";

const FormItem = Form.Item;
const Search = Input.Search;
const confirm=Modal.confirm;

class OrganizationView extends Component {
  constructor(props) {
    super(props);
    this.initPath = [{name: "组织机构管理"}];
    this.state = {
      treeData: [],
      searchValue: "",
      selectedNode: {},
      tableData: [],
      findResultData: [],
      treeSelectedKeys: [],
      modalVisible: false,
      confirmLoading: false,
    }
  }

  componentWillMount() {
    this.getTreeData();
  }

  onModalRef = (ref) => {
    this.modalRef = ref;
  };

  //网络请求树控件数据（组织机构）
  getTreeData = (param) => {
    this.props.show();
    return getOrganizationTree(param).then((result) => {
      let treeData = [];
      if (result) {
        treeData.push(result)
      }
      this.setState({treeData});
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    });
  };

  //树节点选择触发
  onTreeSelect = (selectedKeys, selectedNodes) => {
    this.setState({selectedNode:selectedNodes[0]?selectedNodes[0]:{}})
    let data = selectedNodes[0];
    let categoryForm = {};
    if (data) {
      categoryForm = {
        parentId: data.parentId ? data.parentId : "",
        id: data.id ? data.id : "",
        code: data.code ? data.code : '',
        name: data.name ? data.name : "",
        rank: data.rank ? data.rank : data.rank === 0 ? 0 : "",
        frozen: !!(data.frozen && data.frozen === true)
      };
    }
    this.props.form.setFieldsValue(categoryForm);
    this.setState({treeSelectedKeys: selectedKeys, selectedNode: data});
  };

  judgeTreeSelected = () => {
    if (this.state.selectedNode.id) {
      return true;
    }
    message.error("请选择一个节点");
    return false;
  };

  //增加节点
  onAddNodeClick = () => {
    if (!this.judgeTreeSelected()) return;
    let data = this.state.selectedNode;
    let modalForm = {parentId: data.id, flag: "add", parentName: data.name};
    this.setState({modalForm, modalVisible: true})
  };

  getNodeByKey = (treeData, key) => {
    for (let item of treeData) {
      if (item.id === key) {
        return item
      } else {
        if (item.children.length > 0) {
          if (this.getNodeByKey(item.children, key)) {
            return this.getNodeByKey(item.children, key);
          }
        }
      }
    }
  };

  //删除节点
  onDeleteNodeClick = () => {
    if (!this.judgeTreeSelected()) return;
    let param = this.state.treeSelectedKeys[0];
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        deleteNode(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            //请求treeData数据刷新本地数据
            thiz.props.form.resetFields();
            thiz.getTreeData().then(res=>thiz.setState({selectedNode:{}}));
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
        })
      },
      onCancel() {
      },
    });
  };

  handleEditOrganization = () => {
    //表单数据同步
    if (this.modalRef && this.modalRef.props.form) {
      this.modalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          this.setState({confirmLoading: true});
          if (!values.frozen) {
            values.frozen = false;
          }
          save(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //请求treeData数据刷新本地数据
              this.getTreeData();
              this.setState({confirmLoading: false, modalVisible: false});
            } else {
              message.error(result.message ? result.message : "保存失败")
              this.setState({confirmLoading: false});
            }
          }).catch(err => {
            this.setState({confirmLoading: false});
          })
        }
      })
    }
  };

  saveEdit = () => {
    //表单数据同步
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.props.show()
        save(values).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "保存成功");
            //请求treeData数据刷新本地数据
            this.getTreeData();
          } else {
            message.error(result.message ? result.message : "保存失败")
          }
        }).catch(err => {
        }).finally(() => {
          this.props.hide()//modal的进度条
        });
      }
    });
  };
  handleModalCancel = () => {
    this.setState({modalVisible: false})
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const {selectedNode}=this.state;
    const formItemLayout = {
      labelCol: {
        span: 3
      },
      wrapperCol: {
        span: 8
      },
    };

    const buttons = () => {
      return [
        <CheckAuth
          operateCode="	BASIC-YHGL-ZZJG-ADD"
          key={'nodeCreat'}
        >
        <Button className={"primaryButton"} type={"primary"}
                onClick={this.onAddNodeClick}>创建节点</Button>
        </CheckAuth>,
        <CheckAuth
          operateCode="	BASIC-YHGL-ZZJG-DELETE"
          key={'delete'}
        >
        <Button
                onClick={this.onDeleteNodeClick}>删除</Button>
        </CheckAuth>
      ]
    };
    return (
      <HeadBreadcrumb
        // pathData={this.initPath}
        className={"allocation-page"}
        style={{overflow: "hidden"}}
      >
        {/*左边的树状控件*/}
        <Row
          gutter={rowGutter}
          style={{height: "100%"}}
        >
          <Col span={10} style={{height: "100%"}}>
            <DetailCard
              title="组织机构"
              style={{height: "100%"}}
              bodyStyle={{height: "calc(100% - 53px)"}}
            >
              <StandardTree
                leftExtra={buttons()}
                onSelect={this.onTreeSelect}
                dadaSource={this.state.treeData}
                moveService={move}
                initService={this.getTreeData}/>
              <EditOrganizationModal
                modalVisible={this.state.modalVisible}
                confirmLoading={this.state.confirmLoading}
                handleOk={this.handleEditOrganization}
                handleCancel={this.handleModalCancel}
                onRef={this.onModalRef}
                defaultValue={this.state.modalForm ? this.state.modalForm : {}}
              />
            </DetailCard>

          </Col>

          {/*右边的控件*/}

          <Col span={14} style={{height: "100%"}}>
            <DetailCard
              className={"child-card"}
              style={{height: "100%"}}
              title={this.state.selectedNode.name ? this.state.selectedNode.name : "详细信息"}
            >

              <Form className="card-body-content" style={{height: "100%"}}>
                <Row>
                  <FormItem
                    {...formItemLayout}
                    label="代码">
                    {getFieldDecorator('code', {
                      rules: [{required: true, message: '请填写代码!'},checkInputCode()]
                    })(
                      <Input disabled={true}/>
                    )}
                  </FormItem>
                </Row>
                <Row>
                  <FormItem
                    {...formItemLayout}
                    label="名称">
                    {getFieldDecorator('name', {
                      rules: [{required: true,whitespace:true,max:50, message: '请填写名称!'}]
                    })(
                      <Input maxLength={50} disabled={selectedNode?selectedNode.parentId === null:false}/>
                    )}
                  </FormItem>
                </Row>
                <Row>
                  <FormItem
                    {...formItemLayout}
                    label="排序">
                    {getFieldDecorator('rank', {
                      rules: [{required: true, message: '请填写排序!'}]
                    })(
                      <InputNumber maxLength={9} precision={0} min={0} style={{width: "100%"}}  disabled={selectedNode?selectedNode.parentId === null:false}/>
                    )}
                  </FormItem>
                </Row>
                <Row>
                  <FormItem
                    {...formItemLayout}
                    label="冻结">
                    {getFieldDecorator('frozen', {
                      valuePropName: 'checked',
                    })(
                      <Checkbox/>
                    )}
                  </FormItem>
                </Row>

                <FormItem
                  style={{display: "none"}}>
                  {getFieldDecorator('parentId', {})(
                    <Input disabled/>
                  )}
                </FormItem>
                <FormItem
                  style={{display: "none"}}>
                  {getFieldDecorator('id', {})(
                    <Input disabled/>
                  )}
                </FormItem>
                <br/>
                <Row>
                  <Col span={3}> </Col>
                  <Col span={8}>
                    <CheckAuth
                      operateCode="	BASIC-YHGL-ZZJG-SAVE"
                      key={'delete'}
                    >
                    <Button type={"primary"} onClick={this.saveEdit}>保存</Button>
                    </CheckAuth>
                  </Col>
                </Row>
              </Form>
            </DetailCard>
          </Col>
        </Row>
      </HeadBreadcrumb>

    )
  }
}

const mapStateToProps = (state) => {
  return {};
};

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    },
  }
};
OrganizationView = Form.create()(OrganizationView);
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageOperateHoc(OrganizationView))

